package com.jinzhi.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.Tree;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.oss.domain.FileDO;
import com.jinzhi.oss.service.FileService;
import com.jinzhi.sys.domain.MenuDO;
import com.jinzhi.sys.service.MenuService;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * </pre>
 * <small> 2018年3月23日 | Aron</small>
 */
@Controller
@AllArgsConstructor
public class AdminController extends BaseController {

    private MenuService menuService;
    private FileService fileService;
    private MpConfigService mpConfigService;
    private UserRoleService userRoleService;
    private RoleService roleService;
    @Autowired
    UserService userService;

    @GetMapping({"/", ""})
    String welcome(Model model) {
        return "redirect:/login";
    }

    @GetMapping({"/index"})
    String index(Model model) {
        Long userId = getUserId();
        List<Tree<MenuDO>> menus = menuService.listMenuTree(userId);
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        model.addAttribute("username", getUser().getUsername());
        FileDO fileDO = fileService.selectById(getUser().getPicId());
        model.addAttribute("picUrl", fileDO == null ? "/img/photo_j.jpg" : fileDO.getUrl());
        List<MpConfigDO> mpList = mpConfigService.selectList(null);
        model.addAttribute("mpList", mpList);
        return "aHomeProducts/Home/index1";
    }
//    @GetMapping({"/index111"})
//    String index111(Model model) {
//        Long userId = getUserId();
//        List<Tree<MenuDO>> menus = menuService.listMenuTree(userId);
//        model.addAttribute("menus", menus);
//        model.addAttribute("name", getUser().getName());
//        model.addAttribute("username", getUser().getUsername());
//        FileDO fileDO = fileService.selectById(getUser().getPicId());
//        model.addAttribute("picUrl", fileDO == null ? "/img/photo_j.jpg" : fileDO.getUrl());
//        List<MpConfigDO> mpList = mpConfigService.selectList(null);
//        model.addAttribute("mpList", mpList);
//        return "aHomeProducts/Home/index";
//
//    }
    @GetMapping("/login")
    String login() {
//        return "login2";
        return "aHomeProducts/login";
//        return "aHomeProducts/app";
    }
    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    Result<?> ajaxLogin(@RequestBody UserDO myuser) {
        UsernamePasswordToken token = new UsernamePasswordToken(myuser.getUsername(), myuser.getPassword());

//        token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
                return Result.ok();
        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
        }
    }

    @Log("退出登录")
    @GetMapping("/certificate/loginOut")
    @ResponseBody
    Result<?> loginOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.ok();
    }

    @Log("存储用户选择的机构")
    @PostMapping("/org")
    @ResponseBody
    Result<String> org(Long orgId , HttpServletRequest req) {

        /*HttpSession session = req.getSession();
        session.setAttribute("orgId", orgId);*/

        req.getSession().setAttribute("orgId" , orgId);

        return Result.ok();
    }


    @GetMapping("/main")
    String main(Model model , HttpServletRequest req) {
        UserDO userDO = userService.selectById(this.getUserId());
        model.addAttribute("name", userDO.getUsername());

//        List<String> roleNames = userRoleService.selroleNameList(this.getUserId());
//        model.addAttribute("roleNames", roleNames);
//        req.getSession().setAttribute("roleNames" , roleNames);
//
//        EntityWrapper entityWrapper = new EntityWrapper();
//        int stuAllNum;
//        int eroomAllNum;
//        if(roleNames.indexOf("超级用户角色") > -1) {
//           // stuAllNum = stuSignUpService.selectCount(entityWrapper);
//           // eroomAllNum = examinationRoomService.selectCount(entityWrapper);
//
//          //  int orgAllNum = organizationRolesService.selectCount(entityWrapper);
//            model.addAttribute("orgAllNum",0);
//
//          //  int expAllNum = expertsService.selectCount(entityWrapper);
//            model.addAttribute("expAllNum",0);
//
//         //   int stuNoReview = stuSignUpService.selNoReviewAll();
//            model.addAttribute("stuNoReview",0);
//          //  int orgNoReview = organizationRolesService.selNoReviewAll();
//            model.addAttribute("orgNoReview",0);
//         //   int expNoReview = expertsService.selNoReviewAll();
//            model.addAttribute("expNoReview",0);
//         //   int eroomNoReview = examinationRoomService.selNoReviewAll();
//            model.addAttribute("eroomNoReview",0);
//        }else{
//          //  stuAllNum = stuSignUpService.selNoReview(this.getUser().getOrgId());
//           // eroomAllNum = examinationRoomService.selNoReview(this.getUser().getOrgId());
//        }
//        model.addAttribute("stuAllNum",0);
//        model.addAttribute("eroomAllNum",0);

        return "main";
    }

    @GetMapping("/403")
    String error403() {
        return "403";
    }


    @Log("查询系统收入")
    @PostMapping("/earning")
    @ResponseBody
    Result<?> earning(HttpServletRequest req) {

        Object obj = req.getSession().getAttribute("roleNames");

        String objs = obj.toString().replace("[", "").replace("]" ,"");
        String[] roleNames = objs.split(",");

        for (int i= 0; i < roleNames.length; i++){
            if (roleNames[i] == "超级用户角色" || roleNames[i].equals("超级用户角色")){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Map map = new HashMap();


                map.put("capitalDay" , 0);
                map.put("capitalCount" , 0);
                return Result.ok(map);
            }
        }
        return Result.fail();
    }

}